package com.ruoyi.common.mongo;


import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.common.utils.sign.Base64;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class MongoUtils {
    private static GridFsTemplate gridFsTemplate;

    public static GridFsTemplate gridFsTemplate() {
        if (null == gridFsTemplate) {
            gridFsTemplate = SpringUtils.getBean(GridFsTemplate.class);
        }
        return gridFsTemplate;
    }

    /**
     * 删除附件
     *
     * @param fileName 文件名
     * @return
     */
    public static void deleteFile(String fileName) {
        gridFsTemplate().delete(new Query(Criteria.where("filename").is(fileName)));
    }

    /**
     * 下载附件
     *
     * @param fileName 文件名
     * @return
     */
    public static String getFileToBase64(String fileName) {
        GridFSFile result = gridFsTemplate().findOne(new Query(Criteria.where("filename").is(fileName)));
        if (ToolUtil.isNotEmpty(result)) {
            GridFsResource resource = gridFsTemplate().getResource(result);
            try {
                byte[] bytes = IOUtils.toByteArray(resource.getInputStream());
                return Base64.encode(bytes);
            } catch (IOException ignored) {
            }
        }
        return null;
    }

    /**
     * 下载附件
     *
     * @param fileName 文件名
     * @return
     */
    public static void getFile(String fileName) {
        GridFSFile result = gridFsTemplate().findOne(new Query(Criteria.where("filename").is(fileName)));
        if (ToolUtil.isNotEmpty(result)) {
            GridFsResource resource = gridFsTemplate().getResource(result);
            InputStream inputStream = null;
            ServletOutputStream outputStream = null;
            try {
                HttpServletResponse response = ServletUtils.getResponse();
                byte bs[] = new byte[1024];
                inputStream = resource.getInputStream();
                outputStream = response.getOutputStream();
                response.setContentType("application/octet-stream");
                response.setHeader("Content-disposition", "attachment;filename=" + resource.getFilename());
                while (inputStream.read(bs) > 0) {
                    outputStream.write(bs);
                }
            } catch (IOException ignored) {
            } finally {
                if (ToolUtil.isNotEmpty(inputStream)) {
                    try {
                        inputStream.close();
                    } catch (Exception ignored) {
                    }
                }
                if (ToolUtil.isNotEmpty(outputStream)) {
                    try {
                        outputStream.close();
                    } catch (Exception ignored) {
                    }

                }
            }
        }
    }

    /**
     * 上传附件
     *
     * @param file s
     * @return
     */
    public static String addFile(MultipartFile file) {
        try {
            return addFile(file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 上传附件
     *
     * @param base64
     * @return 文件名
     */
    public static String addFile(String base64) {
        try {
            return addFile(new ByteArrayInputStream(Base64.decode(base64)));
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 上传附件
     *
     * @param inputStream
     * @return
     */
    public static String addFile(InputStream inputStream) {
        DBObject metaData = new BasicDBObject();
        metaData.put("createdDate", DateUtils.getTime());
        String fileName = UUID.fastUUID() + ".jpg";
        gridFsTemplate().store(inputStream, fileName, "image", metaData);
        return fileName;
    }
}
